const mysql = require('mysql2/promise');

async function main() {
    const db = {
        host: process.env.DB_HOST || '43.143.253.188',
        port: parseInt(process.env.DB_PORT || '3306', 10),
        user: process.env.DB_USER || 'nextjs',
        password: process.env.DB_PASS || 'yEAiRE2jcxTyRBy5',
        database: process.env.DB_NAME || 'nextjs',
    };

    let conn;
    try {
        conn = await mysql.createConnection(db);
        const [rows] = await conn.execute(
            'SELECT level, experience, standard_exp_per_fight FROM level_experience WHERE level BETWEEN 11 AND 120 ORDER BY level ASC'
        );
        if (!rows || rows.length === 0) {
            throw new Error('level_experience 无数据');
        }

        const levelMap = new Map(rows.map(r => [Number(r.level), {
            exp: Number(r.experience || 0),
            spf: Number(r.standard_exp_per_fight || 0)
        }]));

        function sumFights(minLevel, maxLevel) {
            let fights = 0;
            for (let lvl = minLevel; lvl <= maxLevel; lvl++) {
                const rec = levelMap.get(lvl);
                if (!rec) throw new Error(`缺少 level=${lvl} 的配置`);
                if (rec.spf <= 0) throw new Error(`level=${lvl} standard_exp_per_fight 非法`);
                fights += rec.exp / rec.spf;
            }
            return fights; // 小数，最终统一向上取整
        }

        // 区间 fights（按小数累加，最后统一向上取整）
        const fights_11_40 = sumFights(11, 40);
        const fights_41_70 = sumFights(41, 70);
        const fights_71_99 = sumFights(71, 99); // 升到100级，故止于99→100

        // 每本心法可折算的标准战斗次数
        const perBook_147 = 100; // 11-40
        const perBook_148 = 150; // 41-70
        const perBook_149 = 200; // 71-100

        // 计算需要的书本数量（向上取整）
        const books_147 = Math.ceil(fights_11_40 / perBook_147);
        const books_148 = Math.ceil(fights_41_70 / perBook_148);
        const books_149 = Math.ceil(fights_71_99 / perBook_149);
        const totalBooks = books_147 + books_148 + books_149;

        // 输出结果
        console.log('副将从 11 → 100 级需要：');
        console.log(`- 初级(147) × ${books_147} 本`);
        console.log(`- 高级(148) × ${books_148} 本`);
        console.log(`- 特级(149) × ${books_149} 本`);
        console.log(`= 合计 ${totalBooks} 本`);

        // 同时输出校验信息（可选）
        console.log('\n校验信息:');
        console.log(`- 11-40 累计标准战斗次数(精确和): ${fights_11_40.toFixed(2)}`);
        console.log(`- 41-70 累计标准战斗次数(精确和): ${fights_41_70.toFixed(2)}`);
        console.log(`- 71-99 累计标准战斗次数(精确和): ${fights_71_99.toFixed(2)}`);
    } catch (e) {
        console.error('计算失败:', e && e.message ? e.message : e);
        process.exit(1);
    } finally {
        if (conn) await conn.end();
    }
}

main().catch(e => { console.error(e); process.exit(1); });
